package cn.ztydata.teachingsystem.heaven.dao.redis;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

/**
 * 知识点资源redis操作类
 *
 * @author fanruiping
 * @since 2014-12-16
 */
@Repository
public class KpResourceDao extends BaseRedisDao{
    private static final String key = "teachingSystem:kpUsedTimes:";

    /**
     * 递增知识点被使用次数
     * @param kpId 知识点编号
     * @return Double
     *
     * @author fanruiping
     * @since 2014-12-16
     */
    public Double incrUsedTimes(Long kpId){
        ZSetOperations<String,Long> zSetOperations = redisTemplate.opsForZSet();

        return zSetOperations.incrementScore(key,kpId,1);
    }

    /**
     * 返回使用次数最多的知识点编号集合
     * @param count
     * @return Set
     *
     * @author fanruiping
     * @since 2014-12-16
     */
    public Set<Long> getOrderByUsedTimes(long count){
        ZSetOperations<String,Long> zSetOperations = redisTemplate.opsForZSet();

        long min = 0;

        logger.debug("return kpId set");

        return zSetOperations.range(key, min, count-1);
    }

    /**
     * 获取知识点关联的资源ID
     *
     * @author chenxin
     * @since 2014/12/18
     */
    public Set<Long> getRscIds(final long kpId) {
        SetOperations<String, Long> setOperations = redisTemplate.opsForSet();

        logger.debug("获取知识点关联的资源ID");
        return setOperations.members(KeyUtils.kpResource(kpId));
    }

    /**
     * 判断知识点是否被用
     * @param kpId 知识点ID
     * @return boolean
     *
     * @author cx
     * @since 2015-02-06
     */
    public boolean isUsed(final long kpId) {
        //获取Set操作
        SetOperations<String, Long> setOperations = redisTemplate.opsForSet();

        logger.debug("return 引用知识点的资源ID");
        //获取Set大小
        return setOperations.size(KeyUtils.kpResource(kpId)) > 0;
    }

    /**
     * 查询多个知识点关联资源ID的并集
     * 
     * @param kpIds 知识点ID集合
     * @return Set
     * 
     * @author cx
     * @since 2015/4/6
     */
    public Set<Long> getResIdsByUnion(final List<Long> kpIds) {
        if (kpIds == null || kpIds.isEmpty()) {
            logger.debug("知识点ID集合为空:kpIds == null || kpIds.isEmpty()");
            return Sets.newHashSet();
        }

        //获取Set操作
        SetOperations<String, Long> setOperations = redisTemplate.opsForSet();

        //使用知识点ID生成键名
        List<String> keys = Lists.newArrayList();

        logger.debug("循环知识点ID集合");
        for (Long kpId : kpIds) {
            keys.add(KeyUtils.kpResource(kpId));
        }

        logger.debug("查询多个知识点关联资源ID的并集");
        return setOperations.union(keys.get(0), keys);
    }
}
